<?php
namespace app\admin\controller;

use app\common\lib\Geet;
use think\controller;
use app\common\validate\MouldValidate;
use app\admin\model\Models;
use think\facade\Cache;
use think\Db;
use think\facade\Config;
class Mould extends Common{
	
	protected function initialize()
	{
	    parent::initialize();
	    $this->Models = new Models;
	}
	
	public function index(){
		return $this->fetch();
	}
	public function index_lists(){
		$limit = request()->param('limit');
		$page = request()->param('page');
		$start = ($page-1)*$limit;
		$count = db('models')->count();
		$result = db('models')
					->limit($start,$limit)
					->order('sort asc,id desc')
					->cache('models'.$limit.$page,3600,'models')
					->select();
		// p($result);die;
		foreach($result as $k=>$v){
			if($this->table_exists($v['table_name'])){
				$result[$k]['count'] = db($v['table_name'])->count();
			}else{
				$result[$k]['count'] = 0;
			}
			
		}
		return showTable(0, 'OK', $count ,$result, 200);
		
	}
	
	public function fields(){
		return $this->fetch();
	}
	//添加模型
	public function add(){
		if(request()->isPost()){
			$data = request()->param();
			$validate = new MouldValidate;
			if (!$validate->scene('add')->check($data)) {
				return show(0, $validate->getError(), 0 , 200);
			}else{
				if($this->Models->addModel($data)){
					Cache::clear('models');
					Cache::clear('models_field');
					return show(1, lang('add success'),"", 200);
				}
				
				return show(0, $this->Models->getError(), $this->Models->getError(), 200);
			}
			
		}
		return $this->fetch();
	}
	
	public function edit_fileds(){
		$data = request()->param();
		$result = db('models')->where('id',$data['id'])->find();
		return show(1, '获取成功', $result, 200);
	}
	
	public function edit(){
		if(request()->isPost()){
			$data = request()->param();
			$validate = new MouldValidate;
			if (!$validate->scene('edit')->check($data)) {
				return show(0, $validate->getError(), 0 , 200);
			}else{
				if($this->Models->editModel($data)){
					Cache::clear('models');
					return show(1, lang('edit success'),"", 200);
				}
				
				return show(0, $this->Models->getError(), $this->Models->getError(), 200);
			}
			
		}
		return $this->fetch();
	}
	
	
	//删除模型
	public function dele(){
		$data = request()->param();
		if($this->Models->delModel($data)){
			Cache::clear('models');
			Cache::clear('models_field');
			return show(1, lang('delsuccess'),"", 200);
		}
		return show(0, $this->Models->getError(), $this->Models->getError(), 200);
	}
	
	
	
	
	/**
	 * 检查表是否存在
	 * $table 不带表前缀
	 */
	public function table_exists($table)
	{
	    $table = Config::get("database.prefix") . strtolower($table);
	    if (true == Db::query("SHOW TABLES LIKE '{$table}'")) {
	        return true;
	    } else {
	        return false;
	    }
	}
}